package com.bj58.migrate.helper;

import java.io.File;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
import java.util.PropertyResourceBundle;

public class NameSpaceUtil{

	private static final Properties NAMESPACE_PROPERTIES = new Properties();

	private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog( NameSpaceUtil.class );

	public static final String CONFIG_PATH_PREFIX = "opt/wf/%s";

	static{
		ClassLoader cl = NameSpaceUtil.class.getClassLoader();
		InputStream inputStream = null;
		try{
			inputStream = cl.getResourceAsStream( "META-INF/namespace.properties" );
			if( inputStream != null ){
				PropertyResourceBundle propertyResourceBundle = new PropertyResourceBundle( inputStream );
				Enumeration< String > keys = propertyResourceBundle.getKeys();
				while( keys.hasMoreElements() ){
					String key = keys.nextElement();
					NAMESPACE_PROPERTIES.put( key, propertyResourceBundle.getObject( key ) );
				}
			}
		}
		catch( Exception e ){
			log.warn( e.getMessage() );
		}
		finally{
			if( inputStream != null ){
				try{
					inputStream.close();
				}
				catch( Exception e2 ){
				}
			}
		}
	}

	/**
	 * 获取本机配置目录
	 * 
	 * @return
	 */
	public static File getConfigFolder(){

		String namespace = getString( "namespace", "" );
		return Helper.hasLength( namespace ) ? new File( Helper.getRoot(), String.format( CONFIG_PATH_PREFIX, namespace ) ) : null;
	}

	/**
	 * 在META-INF/namespace.properties文件中按键取String值
	 * 
	 * @param key
	 * @return 有值则返回值，无值则返回null
	 */
	public static String getString( String key, String defaultValue ){

		String result = NAMESPACE_PROPERTIES.getProperty( key );
		return result == null ? defaultValue : result;
	}
}
